package com.tfj.mvp.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.StringRes;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.hyphenate.tfj.R;
import com.tfj.mvp.tfj.detail.VDetailActivity;
import com.tfj.mvp.tfj.per.logreg.VLogActivity;
import com.hitomi.tilibrary.transfer.Transferee;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.tfj.comm.bean.Constant;
import com.tfj.utils.ActivityManagerUtils;
import com.tfj.utils.AlertUtils;
import com.tfj.utils.StatusBarUtil;
import com.tfj.widget.SlidingLayout;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.ButterKnife;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by Hq on 2017/12/21.
 */

public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity {
    public Context mContext;
    public T mPresenter;
    private AlertDialog loading;
    private static Handler handler;
    public String TAG = this.getClass().getSimpleName();
    private int height_statusbar = 0;
    private LinearLayout linearlayout_status;
    public boolean ifNeedStatus = true;
    public CompositeDisposable mCompositeDisposable;
    public boolean ifSliding = true;
    public boolean ifSetLight = true;
    protected Transferee transferee;
    protected DisplayImageOptions options;
    private View backV;
    private View personalV;
    private TextView titleTV;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            boolean result = fixOrientation();
        }
        super.onCreate(savedInstanceState);//子类的super.OnCreate必须在setContentView后调用
        StatusBarUtil.StatusBarLightMode(this);
        ActivityManagerUtils.getInstance().addActivity(this);
        mContext = this;
        if (setContentViewId() != 0) {
            setContentView(setContentViewId());
        } else {
            throw new RuntimeException("layoutResID==-1 have u create your layout?");
        }
        SlidingLayout rootView = new SlidingLayout(this);
        if (ifSliding) {
           // rootView.bindActivity(this);
        }
        if (ifNeedStatus) {
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                height_statusbar = getResources().getDimensionPixelSize(resourceId);
            }
            linearlayout_status = (LinearLayout) findViewById(R.id.linearlayout_status);
            if(linearlayout_status!=null){
                ViewGroup.LayoutParams paras = linearlayout_status.getLayoutParams();
                paras.height = height_statusbar;
                linearlayout_status.setLayoutParams(paras);
            }
        }
        createPresenter();
        ButterKnife.bind(this);
        mCompositeDisposable = new CompositeDisposable();
        initView();
        initTrans();
    }
    /**
     * 设置标题.
     *
     * @param title the title
     */
    public void setTitleText(String title) {
        titleTV = (TextView) findViewById(R.id.title_titlebar_tv);
        if (titleTV != null ) {
            titleTV.setText(title);
        }

    }

    /**
     * 设置返回键
     */
    public void initBack() {
        backV = findViewById(R.id.back_titlebar_iv);
        if (backV != null) {
            backV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }
    @Override
    public void setRequestedOrientation(int requestedOrientation) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            return;
        }
        super.setRequestedOrientation(requestedOrientation);
    }
    private boolean isTranslucentOrFloating(){
        boolean isTranslucentOrFloating = false;
        try {
            int [] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean)m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }
    private boolean fixOrientation(){
        try {
            Field field = Activity.class.getDeclaredField("mActivityInfo");
            field.setAccessible(true);
            ActivityInfo o = (ActivityInfo)field.get(this);
            o.screenOrientation = -1;
            field.setAccessible(false);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    public  void initTrans(){
        options = new DisplayImageOptions
                .Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .resetViewBeforeLoading(true)
                .build();
        transferee = Transferee.getDefault(this);
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
    }
    /**
     * 添加订阅
     */
    public void addDisposable(Disposable mDisposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(mDisposable);
    }

    /**
     * 取消所有订阅
     */
    public void clearDisposable() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
    }

    /**
     * 初始化方法
     */
    protected void initView() {
        initBack();
    }
    public void toWeb(String url){
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    private Toast mToast;

    public void showToast(final String text) {
        if (mToast == null) {
            mToast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
            mToast.setGravity(Gravity.CENTER,0,0);
        }
        if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mToast.setText(text);
                    mToast.show();
                }
            });
        } else {
            mToast.setText(text);
            mToast.show();
        }
    }
    public void LoadImageUrlRound (ImageView id, String imageurl,int angle){

        RoundedCorners roundedCorners= new RoundedCorners(angle);
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(300, 300);
        options.placeholder(R.mipmap.ic_launcher);
        options.error(R.mipmap.ic_launcher);
        options.diskCacheStrategy(DiskCacheStrategy.RESOURCE);
        options.dontAnimate();
        Glide.with(mContext).load(imageurl).apply(options).thumbnail(Constant.THUMB_PER).into(id);
    }
    public void LoadImageUrl(ImageView id, String imageurl) {
        RequestOptions options = new RequestOptions();
        options.placeholder(R.mipmap.ic_launcher);
        options.error(R.mipmap.ic_launcher);
        options.diskCacheStrategy(DiskCacheStrategy.RESOURCE);
        options.dontAnimate();
        Glide.with(mContext).load(imageurl).thumbnail(Constant.THUMB_PER).apply(options).into(id);
    }
//    public void LoadFresco(SimpleDraweeView placeHolderImageDraweeView, String url , boolean ifRound){
//        GenericDraweeHierarchy hierarchy =   GenericDraweeHierarchyBuilder.newInstance(getResources())
//                .setRoundingParams(ifRound? RoundingParams.asCircle():RoundingParams.fromCornersRadius(0f))
//                .build();
//        /**
//         * 设置淡入淡出效果的显示时间
//         * */
//        hierarchy.setPlaceholderImage(R.mipmap.ic_launcher);
//        DraweeController placeHolderDraweeController = Fresco.newDraweeControllerBuilder()
//                .setUri(url) //为图片设置url
//                .setTapToRetryEnabled(true)   //设置在加载失败后,能否重试
//                .setOldController(placeHolderImageDraweeView.getController())
//                .build();
//        placeHolderImageDraweeView.setController(placeHolderDraweeController);
//        placeHolderImageDraweeView.setHierarchy(hierarchy);
//    }

    public void loadingView(boolean isLoading, String content) {
        if (isLoading) {
            if (loading == null) {
                loading = AlertUtils.loadingDialog(mContext, content);
            }
            if (!loading.isShowing()) {
                loading.show();
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            }
        } else {
            if (loading != null && loading.isShowing()) {
                loading.dismiss();
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            }
        }
    }

    /**
     * 获取contentView 资源id
     */
    public abstract int setContentViewId();

    /**
     * 创建presenter实例
     */
    public abstract void createPresenter();

    /**
     * activity跳转（无参数）
     *
     * @param className
     */
    public void startActivity(Class<?> className) {
        Intent intent = new Intent(mContext, className);
        startActivity(intent);
    }

    /**
     * activity跳转（有参数）
     *
     * @param className
     */
    public void startActivity(Class<?> className, Bundle bundle) {
        Intent intent = new Intent(mContext, className);
        intent.putExtras(bundle);
        startActivity(intent);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroy();//页面销毁 网络请求同销毁
        }
        ButterKnife.bind(this).unbind();
        clearDisposable();
    }

    protected void showKeyboard(boolean isShow) {
        Activity activity = (Activity) mContext;
        if (mContext == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        if (isShow) {
            if (activity.getCurrentFocus() == null) {
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
            } else {
                imm.showSoftInput(activity.getCurrentFocus(), 0);
            }
        } else {
            if (activity.getCurrentFocus() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }

        }
    }

    public void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    public void toLogin() {
        startActivity(VLogActivity.class);
    }
    public void toDetail(String id){
        Intent intent = new Intent (this, VDetailActivity.class);
        intent.putExtra("id",id);
        startActivity(intent);
    }

}
